<template>
  <!-- 
      <img src="/vite.svg" class="logo" alt="Vite logo" />
      <img src="./assets/vue.svg" class="logo vue" alt="Vue logo" /> 
      <Home msg="Vite + Vue" />
      -->
  <Login v-show="(!logined) || userInfo.level < 0 || userInfo.level > 3" v-model:logined="logined" @logined="onlogined">
  </Login>
  <HomeStudent v-if="logined && (userInfo.level > 1)" :user-info="userInfo" @logout="logout"></HomeStudent>
  <HomeTeacher v-if="logined && (userInfo.level == 1)" :user-info="userInfo" @logout="logout"></HomeTeacher>
</template>

<script setup>
import Login from "./components/Login.vue";
import HomeStudent from "./components/HomeStudent.vue";
import HomeTeacher from "./components/HomeTeacher.vue";

import { ref } from "vue";
import * as request from "./api/request"
import {lesson,project,mission,sensorThes} from "./store/index.js"
//此处应该查Storage并验证
const logined = ref(false);
const userInfo = ref({
  id: '',
  name: '',
  level: 0,
  group: 0,
  class: 0,
  token: '',
  code: 0,
  msg: ''
});
try {
  userInfo.value = JSON.parse(localStorage["userInfo"]);
  console.log("历史保存:", userInfo.value);
  if (userInfo.value.token) {
    request.updateToken(userInfo.value.token);
    request.checkToken()
      .then((res) => {
        console.log("checkToken:", res.data);
        if (res.data.code == 0) {
          //token有效
          logined.value = true;
          //如果有收到token，则更新token
          if (res.data.token) {
            userInfo.value.token = res.data.token;
            request.updateToken(res.data.token);
            localStorage["userInfo"] = JSON.stringify(userInfo.value);
          }
          request.post("/user/getlesson",{})
          .then((res)=>{
              lesson.value = res.data.lesson;
              project.value = res.data.project;
              mission.value = res.data.mission;
              sensorThes.value = res.data.sensorThes;
              console.log(JSON.stringify(res.data));
          })
          .catch(res=>{
              console.log(res.response.data);
              alert(JSON.stringify(res.response.data));
          });
        }
      })
      .catch((err) => {
        console.log(err.response);
        //alert(err.response.data.msg);
      });
  }
} catch (e) {
  console.log("无有效登录信息", e);
}
/**
 * 登陆成功后的回调
 * @param {*} value 
 */
function onlogined(value) {
  userInfo.value = value;
}
/**
 * 退出登录
 */
function logout() {
  request.logout()
    .then((res) => {
      console.log(res.data);
      localStorage.removeItem("userInfo");
      request.updateToken('')
      location.reload();
    })
    .catch((err) => {
      console.log(err.response.data);
      alert(err.response.data.msg);
    });
}
</script>

<style>
</style>
